<template>
  <view>
    <view class="maskTime z-999" v-if="showCalendar" @click.stop="showCalendar = false">
      <view class="calendar" @tap.stop="cancel">

        <view class="content" @tap.stop>
          <view class="backgroundBG">
            <image class="backgroundBG_image" :src="`${IMG_URL}/index/timePopupBackground.png`"></image>
          </view>
          <view class="contentAll flex flex-column align-center">
            <view class="title z-9999">
              <view class="sure_cancel flex align-center justify-center" @click.stop="cancel">取消</view>
              <view class="title_content flex flex-column align-center">
                <!--                {{ type === "solar" ? dateInfo.solarDate : dateInfo.lunarDate }}-->
                <text class="title_content_solarDate" :style="{
                  color: type === 'solar' ? '#FF4206' : '#9F9F9F',
                  fontsize: type === 'solar' ? '34rpx' : '32rpx',
                  fontWeight: type === 'solar' ? 'bold' : '500'
                }">{{ dayjs(dateInfo.solarDate).format('YYYY年MM月DD日') }}
                </text>
                <text class="title_content_solarDate" :style="{
                  color: type === 'solar' ? '#9F9F9F' : '#FF4206',
                  fontsize: type === 'solar' ? '32rpx' : '34rpx',
                  fontWeight: type === 'solar' ? '500' : 'bold'
                }">{{ dateInfo.gzYear }}年 {{ lunarYear }} {{ dateInfo.IMonthCn }}{{ dateInfo.IDayCn }}
                </text>
              </view>
              <view class="sure_confirm  flex align-center justify-center" @click.stop="confirmFun">确定</view>
            </view>
            <view style="width: 702rpx;height: 2rpx;background: #DDDDDD;margin-top: 8rpx;"></view>
            <view class="bottom" v-if="isSwitch">
              <view
                class="left  flex align-center justify-center"
                :class="{ active: type === 'solar' }"
                @click="switchBtn('solar')"
              >
                公历
              </view>
              <view
                class="right  flex align-center justify-center"
                :class="{ active: type === 'lunar' }"
                @click="switchBtn('lunar')"
              >
                农历
              </view>
            </view>
            <picker-view :mask-style="'background:transparent;'"
                         :indicator-style="indicatorStyle"
                         :value="selectValue"
                         @change="bindChange"
            >
              <picker-view-column>
                <view class="item" v-for="(item, index) in years" :key="index">
                  {{ item }}
                </view>
              </picker-view-column>
              <picker-view-column>
                <view class="item" v-for="(item, index) in months" :key="index">{{ item }}</view>
              </picker-view-column>
              <picker-view-column>
                <view class="item" v-for="(item, index) in days" :key="index">
                  {{ item }}
                </view>
              </picker-view-column>
            </picker-view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { calendar } from './calendar';
  import dayjs from 'dayjs';
  import sheep from '@/sheep';

  export default {
    name: 'calendar',
    data() {
      return {
        years: [], //年
        months: [], //月
        days: [], //日
        selectValue: [], //默认 [100,0,0] 2000-01-01
        type: '', //lunar农历，solar公历
        dateInfo: {}, // 完整日期数据
        indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth / (750 / 100))}px;background:rgba(255,66,6,0.1);`,
        isFirst: 0,
      };
    },
    props: {
      showCalendar: {
        type: Boolean,
        default: false,
      },
      defaultValue: {
        type: Array,
        default: () => {
          return [86, 0, 0];
        },
      },
      defaultType: {
        type: String,
        default: () => 'solar',
      },
      minYear: {
        type: Number,
        default: () => 1900,
      },
      maxYear: {
        type: Number,
        default: () => 2100,
      },
      isSwitch: {
        type: Boolean,
        default: true,
      },
      // 是否为闰年
      isLeap: {
        type: Boolean,
        default: false,
      },
    },
    components: {},
    computed: {
      IMG_URL() {
        return sheep.$store('AI').sq_image_path;
      },
      lunarYear() {
        if (!this.dateInfo.lYear) {
          return '';
        }
        return calendar.toChinaYear(this.dateInfo.lYear);
      },
    },
    created() {
      this.type = this.defaultType;
      const selectValue = this.defaultValue;
      this.setArray();
      this.setPicker(selectValue, this.type, this.isLeap);
    },
    methods: {
      async setArray() {
        this.getYear();
        this.getMonth();
        this.getDay();
      },
      dayjs,
      // 支持父组件调用设置初值
      async setPicker(selectValue, type, isLeap) {
        this.isFirst = 0;
        // console.log(selectValue, type, isLeap, '当前选择');
        this.$nextTick(async () => {
          this.selectValue = [Number(selectValue[0]), Number(selectValue[1]), Number(selectValue[2])] || this.defaultValue;
          this.$forceUpdate();

          // console.log(this.selectValue);
          this.type = type;

          let val = this.selectValue;
          let year = val[0] + this.minYear;
          let month = 0;
          let leapMonth = calendar.leapMonth(year);
          if (type != 'solar') {

            if (leapMonth != 0) {
              if (leapMonth < month && !isLeap) {
                month = val[1] + 1;
              } else {
                month = val[1];
              }
            } else {
              month = val[1] + 1;
            }
          } else {
            month = val[1] + 1;
          }
          let day = val[2] + 1;

          if (this.type === 'solar') {
            this.setSolarDate(year, month, day);
          } else {
            // console.log(year, month, day, isLeap);
            // this.setLunarDate(year, month, day);
            if (isLeap) {
              const dt = calendar.lunar2solar(year, month, day, isLeap);
              this.setLunarDate(dt.cYear, dt.cMonth, dt.cDay);
            } else {
              if (leapMonth == 0) {
                const dt = calendar.lunar2solar(year, month, day, isLeap);
                this.setLunarDate(dt.cYear, dt.cMonth, dt.cDay);
              } else if (month > leapMonth) {
                const dt = calendar.lunar2solar(year, month, day, isLeap);
                this.setLunarDate(dt.cYear, dt.cMonth, dt.cDay);
              } else {
                const dt = calendar.lunar2solar(year, Number(month) + 1, day, isLeap);
                this.setLunarDate(dt.cYear, dt.cMonth, dt.cDay);
              }
            }
          }
          await this.setArray();
        });
      }
      ,
      getYear() {
        this.years = [];
        if (this.type === 'solar') {
          for (let i = this.minYear; i <= this.maxYear; i++) {
            // 年
            this.years.push(i);
          }
          this.getMonth();
          return;
        }

        if (this.type === 'lunar') {
          for (let i = this.minYear; i <= this.maxYear; i++) {
            // 年
            this.years.push(calendar.toChinaYear(i));
          }
          return;
        }
      }
      ,
      getMonth() {
        this.months = [];
        if (this.type === 'solar') {
          for (let i = 1; i <= 12; i++) {
            //月
            this.months.push(i + '月');
          }
          return;
        }

        if (this.type === 'lunar') {
          const year = this.selectValue[0] + this.minYear;
          const leap_month = calendar.leapMonth(year);
          //返回农历 闰月没有就返回0
          for (let i = 1; i <= 12; i++) {
            this.months.push(calendar.toChinaMonth(i));
            if (i == leap_month) {
              this.months.push('闰' + calendar.toChinaMonth(i));
            }
          }
          return;
        }
      }
      ,
      getDay() {
        this.days = [];
        let year = this.selectValue[0] + this.minYear;
        let month = this.selectValue[1] + 1;
        if (this.type === 'solar') {
          for (let i = 1; i <= calendar.solarDays(year, month); i++) {
            //日
            this.days.push(i + '日');
          }
          if (this.isFirst == 0) {
            let arr = this.selectValue;
            this.selectValue = [0, 0, 0];
            setTimeout(() => {
              this.$nextTick(() => {
                this.selectValue = [Number(arr[0]), Number(arr[1]), Number(arr[2])];
                this.$forceUpdate();
              });
            }, 10);
            this.isFirst = 1;
          }
          return;
        }

        if (this.type === 'lunar') {
          // 农历返回天数
          // **leapMonth 返回闰月 calendar.leapMonth(year)
          // **monthDays 返回非闰月的天数
          // **leapDays 返回闰月的天数
          if (
            calendar.leapMonth(year) != 0 &&
            (calendar.leapMonth(year) == month ||
              month - 1 == calendar.leapMonth(year))
          ) {
            for (
              let i = 1;
              i <= calendar.leapDays(year, calendar.leapMonth(year));
              i++
            ) {
              this.days.push(calendar.toChinaDay(i));
            }
          } else {
            let lunarMonth = '';
            if (calendar.leapMonth(year)) {
              lunarMonth = month < calendar.leapMonth(year) ? month : month - 1;
            } else {
              lunarMonth = month;
            }
            for (let i = 1; i <= calendar.monthDays(year, lunarMonth); i++) {
              this.days.push(calendar.toChinaDay(i));
            }
            if (this.isFirst == 0) {
              let arr = this.selectValue;
              this.selectValue = [0, 0, 0];
              setTimeout(() => {
                this.$nextTick(() => {
                  this.selectValue = [Number(arr[0]), Number(arr[1]), Number(arr[2])];
                  this.$forceUpdate();
                });
              }, 10);
              this.isFirst = 1;
            }
          }
          return;
        }
      }
      ,
      async bindChange(e) {
        let val = e.detail.value;
        this.selectValue = await val;
        await this.setArray();
        const year = val[0] + this.minYear;
        let selectIndex = 0;
        if (this.type != 'solar') {
          selectIndex = calendar.leapMonth(year);
        }
        let month = 0;
        if (this.type != 'solar') {
          if (selectIndex != 0) {
            month = val[1] >= selectIndex ? val[1] : val[1] + 1;
          } else {
            month = val[1] + 1;
          }
        } else {
          month = val[1] + 1;
        }
        const day = val[2] + 1;

        if (this.type === 'solar') {
          this.setSolarDate(year, month, day);
        } else {
          let isLeap = false;
          if (calendar.leapMonth(year) != 0) {
            if (selectIndex == month) {
              if (this.months[val[1]].indexOf('闰') != -1) {
                isLeap = true;
              }
            }
          }
          const dt = calendar.lunar2solar(year, month, day, isLeap);
          this.setLunarDate(dt.cYear, dt.cMonth, dt.cDay);
        }
      }
      ,
      setSolarDate(y, m, d) {
        const dt = calendar.solar2lunar(y, m, d);
        //设置公历数据
        let dateInfo = {
          type: 'solar',
          Animal: dt.Animal,
          astro: dt.astro,
          ncWeek: dt.ncWeek,
          nWeek: dt.nWeek,
          gzYear: dt.gzYear,
          gzMonth: dt.gzMonth,
          gzDay: dt.gzDay,
          IMonthCn: dt.IMonthCn,
          IDayCn: dt.IDayCn,
          festival: dt.festival,
          year: dt.cYear,
          month: dt.cMonth,
          day: dt.cDay,
          solarDate: dt.date,
          lDay: dt.lDay,
          lMonth: dt.lMonth,
          lYear: dt.lYear,
          lunarDate: `${dt.gzYear}年${dt.IMonthCn}${dt.IDayCn}`,
          lunarDateNumber: dt.lunarDate,
          Term: dt.Term,
          isTerm: dt.isTerm,
          isLeap: dt.isLeap,
          isToday: dt.isToday,
          selectValue: [Number(y) - 1900, m, d],
        };
        this.dateInfo = dateInfo;
      }
      ,
      setLunarDate(y, m, d) {
        const dt = calendar.solar2lunar(y, m, d);
        let dateInfo = {
          type: 'lunar',
          Animal: dt.Animal,
          astro: dt.astro,
          ncWeek: dt.ncWeek,
          nWeek: dt.nWeek,
          gzYear: dt.gzYear,
          gzMonth: dt.gzMonth,
          gzDay: dt.gzDay,
          IMonthCn: dt.IMonthCn,
          IDayCn: dt.IDayCn,
          festival: dt.festival,
          year: dt.cYear,
          month: dt.cMonth,
          day: dt.cDay,
          solarDate: dt.date,
          lDay: dt.lDay,
          lMonth: dt.lMonth,
          lYear: dt.lYear,
          lunarDate: `${dt.gzYear}年${dt.IMonthCn}${dt.IDayCn}`,
          lunarDateNumber: dt.lunarDate,
          Term: dt.Term,
          isTerm: dt.isTerm,
          isLeap: dt.isLeap,
          isToday: dt.isToday,
          selectValue: [Number(y) - 1900, Number(dt.lMonth) - 1, Number(dt.lDay) - 1],
        };
        this.dateInfo = dateInfo;
      }
      ,
      cancel() {
        this.$emit('cancel');
      }
      ,
      confirmFun() {
        // 确定
        let dateInfo = this.dateInfo;
        this.$emit('confirm', dateInfo);
      }
      ,

      async switchBtn(type) {
        this.type = type;
        if (type === 'solar') {
          const pickerYear = this.dateInfo.year - this.minYear;
          const pickerMonth = this.dateInfo.month - 1;
          const pickerDay = this.dateInfo.solarDate.split('-')[2] - 1;
          this.selectValue = [pickerYear, pickerMonth, pickerDay];
          this.isFirst = 0;
          await this.setArray();
          const solarYear = this.dateInfo.year;
          const solarMonth = this.dateInfo.month;
          const solarDay = this.dateInfo.day;
          this.setSolarDate(solarYear, solarMonth, solarDay);
        } else {
          const lunarDateArr = this.dateInfo.lunarDateNumber.split('-');
          const pickerYear = Number(lunarDateArr[0]) - this.minYear;
          let month = 0;
          let leapMonth = calendar.leapMonth(Number(lunarDateArr[0]));
          if (leapMonth != 0) {
            if (leapMonth < Number(lunarDateArr[1])) {
              month = Number(lunarDateArr[1]);
            } else if (leapMonth == Number(lunarDateArr[1]) && this.dateInfo.isLeap) {
              month = Number(lunarDateArr[1]);
            } else {
              month = Number(lunarDateArr[1]) - 1;
            }
          } else {
            month = Number(lunarDateArr[1]) - 1;
          }
          const pickerMonth = month;
          const pickerDay = Number(lunarDateArr[2]) - 1;
          // this.$nextTick(() => {
          //   this.selectValue = [pickerYear, pickerMonth, pickerDay];
          //   this.$forceUpdate()
          // })
          this.$set(this, 'selectValue', [pickerYear, pickerMonth, pickerDay]);
          this.isFirst = 0;
          await this.setArray();

          const solarYear = this.dateInfo.year;
          const solarMonth = this.dateInfo.month;
          const solarDay = this.dateInfo.day;
          this.setLunarDate(solarYear, solarMonth, solarDay);
        }
      }
      ,
    },
  };
</script>

<style lang="scss" scope>
  .maskTime {
    /* #ifdef H5 */
    margin: auto;
    /* #endif */
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    box-sizing: border-box;
    background: rgba(0, 0, 0, 0.3);
    z-index: 9999999;
  }

  .u-mask-zoom {
    transform: scale(1, 1);
  }

  .calendar {
    display: flex;
    align-items: flex-end;
    justify-content: center;
    height: 100%;


    .content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 750rpx;
      height: 900rpx;
      background-color: #fff;
      border-top-left-radius: 24rpx;
      border-top-right-radius: 24rpx;

      .backgroundBG {
        width: 750rpx;
        position: fixed;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 900rpx;
        border-top-left-radius: 24rpx;
        border-top-right-radius: 24rpx;
        overflow: hidden;

        .backgroundBG_image {
          width: 100%;
          height: 900rpx;
        }
      }

      .contentAll {
        position: fixed;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 750rpx;
        border-top-left-radius: 24rpx;
        border-top-right-radius: 24rpx;
        overflow: hidden;

        .title {
          display: flex;
          flex-direction: row;
          align-items: center;
          height: 115rpx;
          width: 100%;
          justify-content: space-between;
          border-top-left-radius: 24rpx;
          border-top-right-radius: 24rpx;
          /* #ifdef MP-WEIXIN */
          margin-top: 0;
          /* #endif */
          .left {
            color: #666666;
            font-size: 30rpx;
            padding-left: 30rpx;
          }

          .sure_cancel {
            width: 114rpx;
            height: 50rpx;
            background: #BABABA;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 30rpx;
            color: #FFFFFF;
            border-radius: 40rpx 40rpx 40rpx 40rpx;
            margin-left: 25rpx;
          }

          .title_content {
            .title_content_solarDate {
              font-family: PingFang SC, PingFang SC;
              font-weight: 500;
              font-size: 32rpx;
              color: #4B4B4B;
            }
          }

          .sure_confirm {
            width: 114rpx;
            height: 50rpx;
            background: #FF4206;
            border-radius: 40rpx 40rpx 40rpx 40rpx;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 30rpx;
            color: #FFFFFF;
            margin-right: 25rpx;
          }
        }

        picker-view {
          width: 100%;
          height: 650rpx;
          margin-top: 20rpx;

          ::v-deep .item {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333333;
            font-size: 32rpx;
            font-weight: 500;
          }

          .uni-picker-view-wrapper {
            uni-picker-view-column {
              display: flex;
              align-items: center;
              justify-content: center;
              color: #333333;
              font-size: 32rpx;
              font-weight: 500;

              .uni-picker-view-group {
                .uni-picker-view-content {
                  text-align: center;
                  line-height: 110rpx;

                  .item {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #333333;
                    font-size: 32rpx;
                    font-weight: 500;
                  }
                }
              }
            }
          }
        }

        .bottom {
          height: 110rpx;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;


          .left {
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 36rpx;
            color: #9F9F9F;
            width: 70rpx;
            padding: 14rpx 0;
            margin-right: 54rpx;
            white-space: nowrap;
          }

          .right {
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 36rpx;
            color: #9F9F9F;
            width: 70rpx;
            padding: 14rpx 0;
            margin-left: 54rpx;
            white-space: nowrap;
          }

          .bg {
            background-color: #eb344a;
            color: #333333;
            height: 70rpx;
            border-radius: 40rpx;
            width: 90rpx;
            position: absolute;
            // right: 0;
            top: 0;
            z-index: 0;
          }

          .active {
            font-weight: 700 !important;
            color: #FF4206;
            border-bottom: 2rpx solid #FF4206;
          }

          .lunar {
            left: 90rpx;
            animation: switchsolar 500ms;
          }

          @keyframes switchsolar {
            0% {
              left: 0;
            }
            100% {
              left: 90rpx;
            }
          }

          .solar {
            left: 0;
            animation: switchlunar 500ms;
          }

          @keyframes switchlunar {
            0% {
              left: 90rpx;
            }
            100% {
              left: 0;
            }
          }
        }
      }

    }
  }
</style>
